package services;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConfigManager implements Runnable{
	public ConfigManager()
	{
		
	}
	
	public static void loadProperties()
	{
		int retryTimes = 3;
		Properties pConfiguration = new Properties();
		//File fWorkSpace = new File(DataCache.sWorkSpace);
		File fConfig = new File(DataCache.sConfigFile);
		
		while (retryTimes > 0){
			try {
				FileInputStream properFIS = new FileInputStream(DataCache.sConfigFile);
				pConfiguration.load(properFIS);
				
				if (!pConfiguration.getProperty(DataCache.eDataSections.CourseMatrix.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.CourseMatrix.toString(), 
							pConfiguration.getProperty(DataCache.eDataSections.CourseMatrix.toString()));
				}
				if (!pConfiguration.getProperty(DataCache.eDataSections.VAMatrix.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.VAMatrix.toString(), 
							pConfiguration.getProperty(DataCache.eDataSections.VAMatrix.toString()));
				}
				if (!pConfiguration.getProperty(DataCache.eDataSections.PBTemplate.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.PBTemplate.toString(), 
							pConfiguration.getProperty(DataCache.eDataSections.PBTemplate.toString()));
			    }
				if (!pConfiguration.getProperty(DataCache.eDataSections.Dictionary.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.Dictionary.toString(),
							pConfiguration.getProperty(DataCache.eDataSections.Dictionary.toString()));
				}
				if (!pConfiguration.getProperty(DataCache.eDataSections.ROW.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.ROW.toString(),
							pConfiguration.getProperty(DataCache.eDataSections.ROW.toString()));
				}
				if (!pConfiguration.getProperty(DataCache.eDataSections.NAM.toString()).isEmpty()){
					DataCache.mConfigOption.put(DataCache.eDataSections.NAM.toString(), 
							pConfiguration.getProperty(DataCache.eDataSections.NAM.toString()));
				}
				retryTimes = 0;
				properFIS.close();
				}
			catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				try {
					File dir = new File(".");
					String[] RegPatterns = {"[Cc]ourse.*[Mm]atrix.*\\.[Xx][Ll][Ss][Xx]$",
							"[Vv][Aa].*[Vv][Mm][Ww]are.*based.*[Cc]lasses.*pre.*\\.[Xx][Ll][Ss][Xx]$",
							"[Pp]od[Bb]ooking.*\\.[Xx][Ll][Ss][Xx]$",
							"^Dictionary$",
							"^[0-9]{4}(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])[Ii]nstructor[Pp]a[c]{0,1}kROW\\.[Xx][Ll][Ss][Xx]$",
							"^[0-9]{4}(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])[Ii]nstructor[Pp]a[c]{0,1}k.*NA\\.[Xx][Ll][Ss][Xx]$"};
					String[] children = dir.list();
					
					Map<Integer, String> filename = new HashMap<Integer, String>();
					Pattern p;
					Matcher m;
					for (int j=0; j<RegPatterns.length; j++){
						if (children != null) {
						    for (int i=0; i<children.length; i++) {
						    	
						    	p = Pattern.compile(RegPatterns[j],Pattern.CASE_INSENSITIVE);
								m = p.matcher(children[i]);
								if (m.matches()) {
									filename.put(j, children[i]);
									break;
								}
								else {
									filename.put(j, "n/a");
								}
						    }
						}
					}
					fConfig.createNewFile();					
					
					DataCache.mConfigOption.put(DataCache.eDataSections.CourseMatrix.toString(), filename.get(0)); 
					DataCache.mConfigOption.put(DataCache.eDataSections.VAMatrix.toString(), filename.get(1));
					DataCache.mConfigOption.put(DataCache.eDataSections.PBTemplate.toString(), filename.get(2));  
					DataCache.mConfigOption.put(DataCache.eDataSections.Dictionary.toString(), filename.get(3));
					DataCache.mConfigOption.put(DataCache.eDataSections.ROW.toString(), filename.get(4));  
					DataCache.mConfigOption.put(DataCache.eDataSections.NAM.toString(), filename.get(5));
					saveProperties();
					System.out.println("No configure file found, create new one.");
					} catch (IOException e2){
					retryTimes --;
					}
				}
			catch (IOException e){
					retryTimes --;
				}
			catch (java.lang.NullPointerException e){
				System.out.println("Incorrect configure file.");
				fConfig.delete();
			}
		}
	}
	
	public static void saveProperties()
	{
		Properties pTmp = new Properties();
		try {
		FileOutputStream savingS = new FileOutputStream(DataCache.sConfigFile);
		
		Iterator proItem = DataCache.mConfigOption.entrySet().iterator();
		
		while (proItem.hasNext()) { 
			    Map.Entry entry = (Map.Entry) proItem.next(); 
			    pTmp.setProperty((String) entry.getKey(),(String) entry.getValue()); 
		}		
		pTmp.store(savingS, "ConfigManager");
		savingS.close();
		}
		catch (IOException e)
		{
			
		}
	}
	
	public static void saveProperty(Map<String,String> properties, String key, String value)
	{
		properties.put(key, value);
		
		Properties prop = new Properties();
		try {
		FileOutputStream savingS = new FileOutputStream(DataCache.sConfigFile);
		Iterator proItem = properties.entrySet().iterator();
		
		while (proItem.hasNext()) { 
			    Map.Entry entry = (Map.Entry) proItem.next(); 
			    prop.setProperty((String) entry.getKey(),(String) entry.getValue()); 
		}		
		prop.store(savingS, "ConfigManager");
		savingS.close();
		}
		catch (IOException e)
		{
			
		}

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		loadProperties();
	}
}
